package cn.bqjr.eily.samples.common.shiro;

import cn.bqjr.eily.samples.entity.po.LoginLog;
import cn.bqjr.eily.samples.service.base.ILoginLogService;
import cn.bqjr.eily.samples.utils.ShiroUtils;
import cn.bqjr.eily.utils.IdWorker.IdWorker;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * Auth日志 异步任务
 */
@Component
public class AuthLogAsync {

    private static final Logger logger = LoggerFactory.getLogger(AuthLogAsync.class);

    @Autowired
    private ILoginLogService loginLogService;

    /**
     * 新增登录日志
     */
    @Async
    public void insertLoginLog() {
        Subject subject = ShiroUtils.getSubject();
        Session session = subject.getSession();
        if (subject.isAuthenticated()) {
            LoginLog log = new LoginLog();
            log.setLogId(IdWorker.getId());
            log.setUserId(ShiroUtils.getLocalUserId());
            log.setHostAdress(session.getHost());
            log.setLoginDate(session.getStartTimestamp());
            log.setSessionId(session.getId().toString());
            loginLogService.insert(log);
        }
    }

    /**
     * 更新登出日志
     *
     * @param session
     */
    @Async
    public void updateLogoutLog(Session session) {
        LoginLog log = loginLogService.selectOne(
                new EntityWrapper<LoginLog>().eq(LoginLog.SESSIONID, session.getId().toString())
                                             .isNull(LoginLog.LOGOUTDATE));
        if (null != log) {
            log.setLogoutDate(session.getLastAccessTime()); //取最后操作时间
            int interval = Integer.valueOf(
                    String.valueOf(
                            (log.getLogoutDate().getTime() - log.getLoginDate().getTime()) / 1000));
            log.setIntervalSec(interval);
            loginLogService.updateById(log);
        }
    }
}
